package com.twang.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import com.twang.stock.common.http.HttpClientService;
import com.twang.stock.config.redisLock.RedisLockCallback;
import com.twang.stock.config.redisLock.RedisLockTemplate;
import com.twang.stock.entity.*;
import com.twang.stock.entity.ex.BanKuaiStockInfo;
import com.twang.stock.entity.ex.CompanyStockMinutesEx;
import com.twang.stock.mapper.*;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.RedisKey;
import com.twang.stock.utils.date.HolidayCopy;
import com.twang.stock.utils.http.HttpStockUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * 复盘提醒
 */
@Slf4j
@Service
public class MinutesChengJIaoeService {
    /**
     * 流入资金排名
     */
    public static String KAI_PAN_LA_ZI_JIN_OREDER_1="1";


    /**
     * 流出资金排名
     */
    public static String KAI_PAN_LA_ZI_JIN_OREDER_0="0";


    @Autowired
    private CompanyStockMinutesService companyStockMinutesService;

    @Resource
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    @Resource
    private CompanyStockMinutesMapper companyStockMinutesMapper;

    @Resource
    private ZhangTingBanMapper zhangTingBanMapper;

    @Autowired
    private CommonService commonService;

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;


    @Resource
    private KaiPanLaZhangTingInfoMapper kaiPanLaZhangTingInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private StockHotInfoMapper stockHotInfoMapper;

    @Autowired
    private RedisLockTemplate redisLockTemplate;


    public static String STOCK_TRADE_SUM = "stock_trade_sum";
    private static int DEFAULT_VALUE_亿 = 100000000;

    public void excute() {
        log.info("============> 执行成交额初始化开始");
        chengJiaoECache();
        //
        try {
            板块主页(new ModelAndView());
        } catch (InterruptedException e) {
            log.error("执行error ->{}", e);
            e.printStackTrace();
        }
    }


    public void chengJiaoECache() {
        //涨停原因-缓存
        try {
            List<DfcfBanKuaiMaoLiLv> dfcfBanKuaiMaoLiLvList = chengJiaoE();
            //看点
            initKanDian(dfcfBanKuaiMaoLiLvList, Boolean.TRUE);

            //30 Min 成交额
            getTrade30MinutesVol(dfcfBanKuaiMaoLiLvList);

            //Catche
            String str = JSONObject.toJSONString(dfcfBanKuaiMaoLiLvList);
            redisUtil.set(STOCK_TRADE_SUM, str);
        } catch (Exception e) {
            log.error("{}", e);
        }
    }

    public void getTrade30MinutesVol(List<DfcfBanKuaiMaoLiLv> dfcfBanKuaiMaoLiLvList) {
        dfcfBanKuaiMaoLiLvList.forEach(item -> {
            BigDecimal today30MinVol = BigDecimal.ZERO;
            BigDecimal yesToday30MinVol = BigDecimal.ZERO;
            List<String> days = Lists.newArrayList();
            List<BigDecimal> vols = companyStockMinutesService.getTrade30MinutesVol(item.getCode(), days);
            //
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(vols)) {
                today30MinVol = vols.get(vols.size() - 1);
                yesToday30MinVol = vols.get(vols.size() - 2);
            }
            item.setTradeVol30Min(today30MinVol);
            item.setYesTodayTradeVol30Min(yesToday30MinVol);
            if(item.getYesTodayTradeVol30Min().compareTo(BigDecimal.ZERO)==1){
                item.setLiangBi(item.getTradeVol30Min().divide(item.getYesTodayTradeVol30Min(),2,BigDecimal.ROUND_HALF_UP));
            }else{
                item.setLiangBi(BigDecimal.ZERO);
            }
        });
    }

    public void 板块主页(ModelAndView modelAndView) throws InterruptedException {
        List<String> keyList = Lists.newArrayList(CommonService.AI_COMPUTING_SERVER, CommonService.AI_CPO, CommonService.AI_DATA, CommonService.BK_1, CommonService.BK_2, CommonService.BK_3, CommonService.BK_4, CommonService.BK_5, CommonService.BK_6);
        final CountDownLatch latch = new CountDownLatch(9);
        for (String str : keyList) {
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                try {
                    //AI_COMPUTING_SERVER
                    modelAndView.addObject(str, listByType(str));
                    BaseCommon baseCommon = commonService.getBaseCommon(str);
                    modelAndView.addObject(str + "_NAME", baseCommon.getCommonDesc());
                    modelAndView.addObject(str + "_KEY", baseCommon.getCommonKey());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log.info("============>  gptGaiNian 剩余条数:{}", latch.getCount());
                    latch.countDown();
                }
            });
        }
        modelAndView.addObject("keyList", keyList);
        latch.await();
    }

    /**
     * 涨停原因-缓存
     *
     * @param dfcfBanKuaiMaoLiLvList
     */
    public void initKanDian(List<DfcfBanKuaiMaoLiLv> dfcfBanKuaiMaoLiLvList, Boolean isCache) {
        dfcfBanKuaiMaoLiLvList.stream().forEach(item -> {
            try {
                KaiPanLa kaiPanLa;
                kaiPanLa = getKaiPanLaHisZhangTing(item.getCode());
                if (null != kaiPanLa) {
                    if (!CollectionUtils.isEmpty(kaiPanLa.getList())) {
                        StringBuffer str = new StringBuffer("【").append(kaiPanLa.getList().get(0).getSCLT()).append("】").append(kaiPanLa.getList().get(0).getGNSM());
                        ThsGeGuReZDian thsGeGuReZDian = null;
                        List<ThsGeGuReZDian> kanDian = item.getKanDian();
                        for (ThsGeGuReZDian thsGeGuReZDian1 : kanDian) {
                            List<ThsGeGuReZDian> kanDianTagName = kanDian.stream().filter(a -> "历史涨停原因".equals(thsGeGuReZDian1.getTagName())).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(kanDianTagName) && kanDianTagName.size() > 0) {
                                continue;
                            }
                            if ("历史涨停原因".equals(thsGeGuReZDian1.getTagName())) {
                                thsGeGuReZDian1.setZtDesc(str.toString());
                                continue;
                            } else {
                                thsGeGuReZDian = new ThsGeGuReZDian();
                                thsGeGuReZDian.setTagName("历史涨停原因");
                                thsGeGuReZDian.setZtDesc(str.toString());
                                continue;
                            }
                        }
                        if (null != thsGeGuReZDian) {
                            item.getKanDian().add(thsGeGuReZDian);
                        }
                    }
                }

                //查询概念
                KaiPanLaZhangTingInfo kaiPanLaZhangTingInfo = kaiPanLaZhangTingInfoMapper.queyByCode(item.getCode().replace("sh", "").replace("sz", ""));
                if (null != kaiPanLaZhangTingInfo) {
                    item.setBk(kaiPanLaZhangTingInfo.getZyglbk());
                    item.setZhangTingId(kaiPanLaZhangTingInfo.getId());
                }else{
                    item.setBk("-");
                    item.setZhangTingId(0L);
                }
            } catch (Exception e) {
                log.error("============> 开盘啦获取涨停原因出错：{}", e);
            }
        });
        //只看公司印象
        {
            dfcfBanKuaiMaoLiLvList.forEach(item -> {
                List<ThsGeGuReZDian> kanDianNew = Lists.newArrayList();
                List<ThsGeGuReZDian> kanDian = item.getKanDian();
                for (ThsGeGuReZDian thsGeGuReZDian1 : kanDian) {
//                    if ("历史涨停原因".equals(thsGeGuReZDian1.getTagName()) || "市场印象".equals(thsGeGuReZDian1.getTagName())) {
                      if ("历史涨停原因".equals(thsGeGuReZDian1.getTagName())) {
                            kanDianNew.add(thsGeGuReZDian1);
                    }
                }
                item.setKanDian(kanDianNew);
            });
        }
    }

    /**
     * 获取历史涨停原因
     * @param code
     * @return
     * @throws Exception
     */
    public KaiPanLa getKaiPanLaHisZhangTing(String code) throws Exception {
        KaiPanLa kaiPanLa;
        String key = KaiPanLa.TODAY_ZHANG_TING + "_" + HolidayCopy.getRealToday() + "_" + code;
        Object object = redisUtil.get(key);
        if (null == object) {
            Thread.sleep(1000);
            kaiPanLa = getGetDayZhangTing(code.replace("sh", "").replace("sz", ""));
            log.info("============> 读取第三方：code={}，result={}", code, JSONObject.toJSONString(kaiPanLa));
            redisUtil.set(key, kaiPanLa);
        } else {
            kaiPanLa = (KaiPanLa) object;
            log.info("============> 读取缓存：code={}", code);
        }
        return kaiPanLa;
    }


    public List<DfcfBanKuaiMaoLiLv> chengJiaoE() {
        List<DfcfBanKuaiMaoLiLv> maoLiLvs = Lists.newArrayList();
        try {
            List<CompanyStockMinutes> list = getTradeAmountDESC(null, companyStockMinutesMapper.queryYesterDayNew());
            return getDfcfBanKuaiMaoLiLvs(maoLiLvs, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<DfcfBanKuaiMaoLiLv> getDfcfBanKuaiMaoLiLvs(List<DfcfBanKuaiMaoLiLv> maoLiLvs, List<CompanyStockMinutes> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        int number = list.size() > 99 ? 100 : list.size();
        for (int i = 0; i < number; i++) {
            CompanyStockMinutes companyStockMinutes = list.get(i);
            /** * 6-今日大盘 */
            try {
                if (null == companyStockMinutes) {
                    continue;
                }
                String code = companyStockMinutes.getCompanyCode().replace("sz", "").replace("sh", "");
                String stockCode = companyStockMinutes.getCompanyCode();
                DfcfBanKuaiMaoLiLv dfcfBanKuaiMaoLiLv = new DfcfBanKuaiMaoLiLv();
                dfcfBanKuaiMaoLiLv.setCode(code);
                dfcfBanKuaiMaoLiLv.setName(companyStockMinutes.getCompanyName());
                dfcfBanKuaiMaoLiLv.setMll(companyStockMinutes.getZhangDie());
                dfcfBanKuaiMaoLiLv.setZrZhangDie(companyStockMinutesMapper.queryYesterZhangDie(companyStockMinutes.getCompanyCode(), companyStockMinutes.getDate()));
                dfcfBanKuaiMaoLiLv.setLianXuZhang(this.isLianXuShangZhang(dfcfBanKuaiMaoLiLv));
                dfcfBanKuaiMaoLiLv.setCje(companyStockMinutes.getTradeSum());
                List<ThsGeGuReZDian> thsGeGuReZDianList = 查询个股热点(code);
                //查询涨停原因
                ThsGeGuReZDian thsGeGuReZDian = new ThsGeGuReZDian();
                thsGeGuReZDian.setTagName("历史涨停原因");
                String ztDesc = zhangtingReason(stockCode);
                if (StringUtils.isNotBlank(ztDesc)) {
                    thsGeGuReZDian.setZtDesc(ztDesc);
                }
                //
                thsGeGuReZDianList.add(thsGeGuReZDian);
                dfcfBanKuaiMaoLiLv.setKanDian(thsGeGuReZDianList);
                maoLiLvs.add(dfcfBanKuaiMaoLiLv);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("成交额 数据 处理完成 list size={}",list.size());
        return maoLiLvs;
    }

    /**
     * 查询成交额排前的
     *
     * @param minutes
     * @param date
     * @return
     */
    public List<CompanyStockMinutes> getTradeAmountDESC(String minutes, String date) {
        //查询当日成交额前50
        Example example = new Example(CompanyStockMinutes.class);
        Example.Criteria criteria = example.createCriteria();
        //
        if (StringUtils.isNotBlank(minutes)) {
            criteria.andEqualTo("minutes", minutes);
        } else {
            criteria.andEqualTo("minutes", companyStockMinutesMapper.queryNewMinutes());
        }
        //
        if (StringUtils.isNotBlank(date)) {
            criteria.andEqualTo("date", date);
        } else {
            criteria.andEqualTo("date", companyStockMinutesMapper.queryYesterDayNew());
        }
        example.orderBy("tradeSum").desc();
        List<CompanyStockMinutes> list = companyStockMinutesMapper.selectByExample(example);
        return list;
    }


    public Boolean isLianXuShangZhang(DfcfBanKuaiMaoLiLv dfcfBanKuaiMaoLiLv) {
        try {
            if (dfcfBanKuaiMaoLiLv.getMll().compareTo(BigDecimal.ZERO) >= 1 && (dfcfBanKuaiMaoLiLv.getZrZhangDie().compareTo(BigDecimal.ZERO) >= 1)) {
                return Boolean.TRUE;
            }
        } catch (Exception e) {

        }
        return Boolean.FALSE;
    }

    /**
     * 查询个股热点
     *
     * @return
     */
    public static List<ThsGeGuReZDian> 查询个股热点(String code) throws Exception {
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        String url = "https://eq.10jqka.com.cn/open/api/stock_view_v2/homepage?stockCode=" + code + "&marketId=17";
        String result = HttpStockUtils.getHtmlStrByUrlUtf8(url);

        String diff = JsonPath.read(result, "$.data.labels").toString();
        List<ThsGeGuReZDian> list = JSONObject.parseArray(diff, ThsGeGuReZDian.class);
        List<ThsGeGuReZDian> newList = Lists.newArrayList();
        for (int i = list.size() - 1; i >= 0; i--) {
            newList.add(list.get(i));
        }
        return newList;
    }

    public String zhangtingReason(String code) {
        try {
            Example example = new Example(ZhangTingBan.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", code.replace("sh", "").replace("sz", ""));
            example.orderBy("id").desc();
            List<ZhangTingBan> zhangTingBans = zhangTingBanMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(zhangTingBans)) {
                return zhangTingBans.get(0).getZtReason();
            }
        } catch (Exception e) {
            log.error("查询涨停原因失败！，e={}", e);
            throw e;
        }
        return null;

    }

    /**
     * 查询历史
     *
     * @param code
     * @return
     * @throws Exception
     */
    public static KaiPanLa getGetDayZhangTing(String code) throws Exception {
        List<NameValuePair> nameValuePairList = Lists.newArrayList();
        nameValuePairList.add(new BasicNameValuePair("Index", "0"));
        nameValuePairList.add(new BasicNameValuePair("PhoneOSNew", "2"));
        nameValuePairList.add(new BasicNameValuePair("StockID", code));
        nameValuePairList.add(new BasicNameValuePair("VerSion", "5.4.0.0"));
        nameValuePairList.add(new BasicNameValuePair("apiv", "w29"));
        nameValuePairList.add(new BasicNameValuePair("a", "GetDayZhangTing"));
        nameValuePairList.add(new BasicNameValuePair("c", "HisLimitResumption"));
        nameValuePairList.add(new BasicNameValuePair("st", "20"));
        Object str = HttpClientService.sendPost("https://apphis.longhuvip.com/w1/api/index.php", nameValuePairList);
        if (null != str) {
            KaiPanLa kaiPanLa = JSONObject.parseObject(JSONObject.toJSONString(str), KaiPanLa.class);
            return kaiPanLa;
        }
        return null;
    }


    public List<BanKuaiStockInfo> listByType(String typeKey) {
        List<BanKuaiStockInfo> banKuaiStockInfoList = Lists.newArrayList();
        String key = "BanKuaiStockInfo-listByType-" + typeKey;
        Object obj = redisUtil.get(key);
        if (null == obj) {
            String data = commonService.getValue(typeKey);
            String[] codes = data.split(",");
            for (int i = 0; i < codes.length; i++) {
                //初始化信息
                BanKuaiStockInfo banKuaiStockInfo = new BanKuaiStockInfo();
                banKuaiStockInfo.setCompanyCode(codes[i]);
                CompanyStockMinutes companyStockMinutes = companyStockMinutesMapper.queryByCode(codes[i]);
                if (null == companyStockMinutes) {
                    log.error("companyStockMinutes is null company_code={}", codes[i]);
                }
                BeanUtils.copyProperties(companyStockMinutes, banKuaiStockInfo);
                //
                List<CompanyStockMinutes> list = companyStockMinutesMapper.queryYesterDayAndToday(companyStockMinutes.getCompanyCode(), "1000");
                if (!CollectionUtils.isEmpty(list) || list.size() >= 2) {
                    banKuaiStockInfo.setYesterDay30MinVol(初始化单位(list.get(1).getTradeVol()).replace("万", "").replace("亿", ""));
                    banKuaiStockInfo.setToDay30MinVol(初始化单位(list.get(0).getTradeVol()).replace("万", "").replace("亿", ""));
                }

                banKuaiStockInfo.setTodayChengJiaoE(初始化单位(companyStockMinutes.getTradeSum()));
                banKuaiStockInfoList.add(banKuaiStockInfo);
            }
            redisUtil.set(key, JSONObject.toJSONString(banKuaiStockInfoList));
        } else {
            banKuaiStockInfoList = JSONObject.parseArray(obj.toString(), BanKuaiStockInfo.class);
        }
        return banKuaiStockInfoList;
    }


    private String 初始化单位(BigDecimal value) {
        String str = "";
        if (value.compareTo(new BigDecimal(DEFAULT_VALUE_亿)) == 1) {
            str = (value.divide(new BigDecimal(DEFAULT_VALUE_亿)).setScale(2, BigDecimal.ROUND_HALF_UP)).toString() + "亿";
        } else {
            str = (value.divide(new BigDecimal(10000)).setScale(2, BigDecimal.ROUND_HALF_UP)).toString() + "万";
        }
        return str;
    }


    /**
     * 查询资金流向
     * @param rStart
     * @param rEnd
     * @return
     * @throws Exception
     */
    public static List<KaiPanLaZhiJing> getStockMoneyMinutes(String rStart,String rEnd,String order) throws Exception {
        List<KaiPanLaZhiJing> kaiPanLaZhiJings = Lists.newArrayList();
        List<NameValuePair> nameValuePairList = Lists.newArrayList();
        nameValuePairList.add(new BasicNameValuePair("RStart", rStart));//开始时间
        nameValuePairList.add(new BasicNameValuePair("REnd", rEnd));//结束时间
        nameValuePairList.add(new BasicNameValuePair("PhoneOSNew", "2"));
        nameValuePairList.add(new BasicNameValuePair("FilterTIB", "0"));
        nameValuePairList.add(new BasicNameValuePair("VerSion", "5.13.0.3"));
        nameValuePairList.add(new BasicNameValuePair("apiv", "w35"));
        nameValuePairList.add(new BasicNameValuePair("a", "RealRankingInfo_W8"));
        nameValuePairList.add(new BasicNameValuePair("c", "NewStockRanking"));
        nameValuePairList.add(new BasicNameValuePair("Ratio", "6"));
        nameValuePairList.add(new BasicNameValuePair("Order", order));//1-流入，0-流出
        nameValuePairList.add(new BasicNameValuePair("index", "0"));
        nameValuePairList.add(new BasicNameValuePair("FilterMotherboard", "0"));
        nameValuePairList.add(new BasicNameValuePair("Isst", "0"));
        nameValuePairList.add(new BasicNameValuePair("st", "20"));
        nameValuePairList.add(new BasicNameValuePair("Filter", "0"));
        nameValuePairList.add(new BasicNameValuePair("Type", "1"));
        nameValuePairList.add(new BasicNameValuePair("FilterGem", "0"));
        Object str = HttpClientService.sendPost("https://apphq.longhuvip.com/w1/api/index.php", nameValuePairList);
        String minutes = HolidayCopy.getHHmmss().substring(8, 12);
        String date = HolidayCopy.getRealToday();
        if (null != str) {
            JSONObject result = (JSONObject) JSONObject.toJSON(str);
            List objectList = (List) result.get("list");
            if (!CollectionUtils.isEmpty(objectList)) {
                objectList.stream().forEach(item -> {
                    KaiPanLaZhiJing kaiPanLaZhiJing = new KaiPanLaZhiJing();
                    List listData = ((List) item);
                    String code = listData.get(0).toString();//code
                    kaiPanLaZhiJing.setCode(code);
                    String name = listData.get(1).toString();//name
                    kaiPanLaZhiJing.setName(name);
                    kaiPanLaZhiJing.setBk(listData.get(4).toString());
                    kaiPanLaZhiJing.setPrice(new BigDecimal(listData.get(5).toString()));
                    kaiPanLaZhiJing.setQuJianAmount(new BigDecimal(listData.get(7).toString()));
                    kaiPanLaZhiJing.setShiJiHuanShou(new BigDecimal(listData.get(8).toString()));
                    kaiPanLaZhiJing.setShiJiLiuTongShiZhi(new BigDecimal(listData.get(10).toString()));
                    kaiPanLaZhiJing.setZhuLiJingBuy(new BigDecimal(listData.get(13).toString()));
                    kaiPanLaZhiJing.setZhenFu(new BigDecimal(listData.get(33).toString()));
                    kaiPanLaZhiJing.setZongShiZhi(new BigDecimal(listData.get(37).toString()));
                    kaiPanLaZhiJing.setQuJianZhangFu(new BigDecimal(listData.get(57).toString()));
                    kaiPanLaZhiJing.setLiangBi(new BigDecimal(listData.get(21).toString()));
                    kaiPanLaZhiJing.setLianBanZhuangTai(listData.get(23).toString());
                    kaiPanLaZhiJing.setCreateTime(new Date());
                    kaiPanLaZhiJing.setUpdateTime(new Date());
                    kaiPanLaZhiJing.setDate(date);
                    kaiPanLaZhiJing.setMinutes(minutes);
                    kaiPanLaZhiJing.setRStart(rStart);
                    kaiPanLaZhiJing.setREnd(rEnd);
                    kaiPanLaZhiJing.setOrderType(order);
                    kaiPanLaZhiJings.add(kaiPanLaZhiJing);
                });
            }
        }
        return kaiPanLaZhiJings;
    }

    public static void main(String[] args) throws Exception {
        getStockMoneyMinutes("1400","1406","1");
    }

    /**
     *
     * @param nextInterval 时间间隔，每个几分钟
     * @return
     */
    public static List<String> generateTimeSequence(int nextInterval) {
        List<String> timeSequence = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        SimpleDateFormat sdf = new SimpleDateFormat("HHmm");

        while (calendar.get(Calendar.HOUR_OF_DAY) < 15 || (calendar.get(Calendar.HOUR_OF_DAY) == 15 && calendar.get(Calendar.MINUTE) == 0)) {
            int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
            int currentMinute = calendar.get(Calendar.MINUTE);

            // Check if the current time is not in the excluded interval (11:35 - 12:55)
            if (!(currentHour == 11 && currentMinute >= 35 && currentHour < 12)
                    && !(currentHour == 12 && currentMinute <= 55)) {
                timeSequence.add(sdf.format(calendar.getTime()));
            }

            // Move to the next 5-minute interval
            calendar.add(Calendar.MINUTE, nextInterval);
        }

        return timeSequence;
    }


    /**
     * 获取
     * 1、今天的市值大于100亿，并且涨幅超过7的
     *
     * 2、市值大于300亿的，涨幅大于5%的
     *
     */
    public List<CompanyStockMinutesEx> getTodayVolumeExceedingBillion(String dateTime) {
        //防止重复生成
        if (StringUtils.isEmpty(dateTime)) {
            StockHotInfo stockHotInfo = new StockHotInfo();
            stockHotInfo.setDate(HolidayCopy.getRealToday());
            List<StockHotInfo> result = stockHotInfoMapper.select(stockHotInfo);
            if (!CollectionUtils.isEmpty(result)) {
                dateTime = stockHotInfo.getDate();
            }
        }
        List<CompanyStockMinutesEx> stockMinutes = Lists.newArrayList();
        if (StringUtils.isNotEmpty(dateTime)) {
            StockHotInfo stockHotInfo = new StockHotInfo();
            stockHotInfo.setDate(dateTime);
            List<StockHotInfo> result = stockHotInfoMapper.select(stockHotInfo);
            List<CompanyStockMinutesEx> obj = JSONObject.parseArray(result.get(0).getInfo(), CompanyStockMinutesEx.class);
            return obj;
        }
        String redisKey = String.format(RedisKey.LOCK_PREFIX, "getTodayVolumeExceedingBillion_identification_");
        redisLockTemplate.execute(redisKey, new RedisLockCallback() {
            @Override
            public Object doInRedisLock() {
                return _getTodayVolumeExceedingBillion(stockMinutes);
            }
        });
        return stockMinutes;

    }

    private List<CompanyStockMinutesEx> _getTodayVolumeExceedingBillion(List<CompanyStockMinutesEx> stockMinutes) {
        List<String> dates = companyStockMinutesMapper.queryDates();
        String date = dates.get(dates.size() - 1);
        String getTodayVolumeExceedingBillion_Key = "getTodayVolumeExceedingBillion:" + date;
        List<CompanyStockMinutesEx> obj = (List<CompanyStockMinutesEx>) redisUtil.get(getTodayVolumeExceedingBillion_Key);
        //cacahe
        if (!CollectionUtils.isEmpty(obj)) {
            stockMinutes.addAll(obj);
        } else {
            //new
            List<CompanyStockMinutesEx> todayVolumeExceedingBillion = companyStockMinutesMapper.getTodayVolumeExceedingBillion(date);
            List<CompanyCodeInfo> companyCodeInfos = companyCodeInfoMapper.selectAll();
            if (!CollectionUtils.isEmpty(todayVolumeExceedingBillion)) {
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                todayVolumeExceedingBillion.stream().forEach(item -> {
                    CompanyCodeInfo targetInfo = companyCodeInfos.stream().filter(info -> info.getCompanyCode().equals(item.getCompanyCode())).findFirst().orElse(null);
                    item.setCompanyCode(item.getCompanyCode().substring(2, 8));
                    if (null != targetInfo && null == stringObjectHashMap.get(item.getCompanyCode())) {
                        //判断市值大于300亿的，涨幅大于5%的
                        if (targetInfo.getMarketValue().compareTo(new BigDecimal(200)) == 1 && item.getZhangDie().compareTo(new BigDecimal(5)) >= 0) {
                            item.setMarketCapitalization(targetInfo.getMarketValue());
                            //获取板块
                            getBanKuaiAndZhangTingReason(item);
                            stockMinutes.add(item);
                            stringObjectHashMap.put(item.getCompanyCode(), item);
                        } else if (targetInfo.getMarketValue().compareTo(new BigDecimal(100)) == 1 && item.getZhangDie().compareTo(new BigDecimal(7)) >= 0) {
                            item.setMarketCapitalization(targetInfo.getMarketValue());
                            //今天的市值大于100亿，并且涨幅超过7的
                            getBanKuaiAndZhangTingReason(item);
                            stockMinutes.add(item);
                            stringObjectHashMap.put(item.getCompanyCode(), item);
                        }
                    }

                });
                redisUtil.set(getTodayVolumeExceedingBillion_Key, stockMinutes, 60 * 60 * 1000 * 24);
                //缓存报文
                {
                    StockHotInfo stockHotInfo = new StockHotInfo();
                    stockHotInfo.setDate(HolidayCopy.getRealToday());
                    stockHotInfo.setNum(stockMinutes.size());
                    stockHotInfo.setInfo(JSONObject.toJSONString(stockMinutes));
                    stockHotInfoMapper.insert(stockHotInfo);
                }
            }
        }
        return stockMinutes;
    }

    /**
     * 获取板块、查询概念
     * @param item
     */
    public void getBanKuaiAndZhangTingReason(CompanyStockMinutesEx item) {
        //获取板块
        extractedGetZhangTingDesc(item);
        //查询概念
        KaiPanLaZhangTingInfo kaiPanLaZhangTingInfo = kaiPanLaZhangTingInfoMapper.queyByCode(item.getCompanyCode().replace("sh", "").replace("sz", ""));
        if (null != kaiPanLaZhangTingInfo) {
            item.setBk(kaiPanLaZhangTingInfo.getZyglbk());
        } else {
            item.setBk("-");
        }
    }

    /**
     * code获取涨停原因
     * @param item
     */
    public void extractedGetZhangTingDesc(CompanyStockMinutesEx item) {
        try {
            KaiPanLa kaiPanLa = getKaiPanLaHisZhangTing(item.getCompanyCode());
            if (null != kaiPanLa) {
                if (!CollectionUtils.isEmpty(kaiPanLa.getList())) {
                    StringBuffer str = new StringBuffer("【").append(kaiPanLa.getList().get(0).getSCLT()).append("】").append(kaiPanLa.getList().get(0).getGNSM());
                    if (StringUtils.isNotEmpty(str)) {
                        item.setZtDesc(str.toString());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}